package station;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;

public class DataSource extends TimerTask {

	private String data;
	private int interval;
	private DatagramSocket socket;
	private DatagramPacket packet;
	private Timer timer;
	private byte[] buffer;
	
//	private static final String CHARSET = "utf-8";
	private static final String HOST = "localhost";
	private static final int BUFFERSIZE = 24;
	
	public DataSource(int port, String team, String station, String data, int interval) {
		this.data = team + "-" + station + " " + data;
		this.interval = interval;
//		this.buffer = new byte[BUFFERSIZE];
		
		this.buffer = this.generateMessage(this.data);
		
		try {
			this.socket = new DatagramSocket();
//			this.buffer = this.data.getBytes(CHARSET);
//			this.buffer = this.data.getBytes();
//			System.out.println(this.buffer.length);
			this.packet = new DatagramPacket(this.buffer, BUFFERSIZE, InetAddress.getByName(HOST), port);
		} catch (SocketException e) {
			e.printStackTrace();
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		
		this.timer = new Timer();
		this.timer.scheduleAtFixedRate(this, 0, this.interval);
	}

	@Override
	public void run() {
		try {
			this.socket.send(this.packet);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private byte[] generateMessage(String message) {
		int length = message.getBytes().length;
		if (length > BUFFERSIZE) {
			message = message.substring(0, BUFFERSIZE - 1);
		} else if (length < BUFFERSIZE) {
			char[] tmp = new char[BUFFERSIZE - length];
			Arrays.fill(tmp, ' ');
			message = message.concat(new String(tmp));
//			System.out.println(message.getBytes().length);
		}
//		return message.getBytes(CHARSET);
		return message.getBytes();
	}
	
}
